package db_main

import (
	"errors"
	"fmt"
	"gorm.io/gorm"
	"longmen/server/pkg/common/helper/util"
	"longmen/server/pkg/db/mysql"
	"longmen/server/pkg/db/mysql/models/models_main"
)

func GetNoticeList(param map[string]interface{}, page int, size int) ([]*models_main.Notice, error) {
	fName := "GetNoticeList"
	if size > 20 {
		size = 20
	}
	if page <= 0 {
		page = 1
	}
	o := make([]*models_main.Notice, 0)
	table := mysql.GetRTable(&models_main.Notice{})
	mysql.Condition(table, param, "", "create_time DESC", page, size)
	err := table.Select("`content`,`link`,`image_url`,`create_time`").Find(&o).Error
	if err != nil {
		err = fmt.Errorf("%s%s", util.Convert(fName), err.Error())
	}
	return o, err
}

func GetNoticeProfile(uid int) (*models_main.Notice, error) {
	fName := "GetNoticeProfile"
	o := &models_main.Notice{}
	err := mysql.GetRTable(&models_main.Notice{}).Where("user_id=?", uid).Order("create_time DESC").Take(&o).Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		err = nil
	}
	if err != nil {
		err = fmt.Errorf("%s%s", util.Convert(fName), err.Error())
	}
	return o, err
}

func InsertNoticeByTx(tx *gorm.DB, notice *models_main.Notice) error {
	fName := "InsertNoticeByTx"
	err := tx.Create(notice).Error
	if err != nil {
		tx.Rollback()
		return fmt.Errorf("%s%s", util.Convert(fName), err.Error())
	}
	return nil
}
